package edu.scau.mis.web.controller.pos;

import edu.scau.mis.core.annotation.RequestLog;
import edu.scau.mis.core.domain.AjaxResult;
import edu.scau.mis.core.enums.BusinessType;
import edu.scau.mis.pos.domain.Change;
import edu.scau.mis.pos.domain.OrderItem;
import edu.scau.mis.pos.service.IChangeService;
import edu.scau.mis.pos.service.IOrderItemService;
import edu.scau.mis.pos.service.IProductService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/changes")
public class ChangeController {

    @Resource
    private IChangeService changeService;

    @Resource
    private IOrderItemService orderItemService;

    @Resource
    private IProductService productService;

    /**
     * 查询换货单列表
     */
    @RequestLog(title = "查询换货单列表",businessType = BusinessType.Query)
    @GetMapping("/list")
    public AjaxResult listChanges(
            @RequestParam(required = false) String changeSn,
            @RequestParam(required = false) String orderId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        // 直接查询数据，不需要手动映射 statusDescription
        List<Change> changes = changeService.listChanges(changeSn, orderId, status, startTime, endTime, pageNum, pageSize);
        return AjaxResult.success(changes);
    }


    /**
     * 确认换货
     */
    @RequestLog(title = "确认换货",businessType = BusinessType.OTHER)
    @PutMapping("/confirm/{changeSn}")
    public AjaxResult confirmChange(@PathVariable String changeSn, @RequestParam String orderId) {
        // 1️⃣ 执行换货状态更新
        boolean success = changeService.confirmChange(changeSn, orderId);

        if (success) {
            // 查询最新数据
            Change updatedChange = changeService.getChangeBySn(changeSn);

            // 2️⃣ 清空订单总价、数量、原价等字段
            boolean clearOrderSuccess = orderItemService.clearOrderPriceAndQuantity(orderId);

            // 3️⃣ 调整库存和销量
            List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderId(orderId);
            for (OrderItem item : orderItems) {
                // 恢复库存
                productService.increaseStock(item.getProductSn(), item.getQuantity());
                // 减少销量
                productService.decreaseSalesVolume(item.getProductSn(), item.getQuantity());
            }

            if (clearOrderSuccess) {
                return AjaxResult.success("换货成功", updatedChange);
            } else {
                return AjaxResult.error("换货失败，清空订单信息失败");
            }
        } else {
            return AjaxResult.error("换货失败");
        }
    }

    @RequestLog(title = "删除换货单",businessType = BusinessType.DELETE)
    //删除换货单
    @DeleteMapping("/delete/{changeSn}")
    public AjaxResult deleteChange(@PathVariable String changeSn) {
        boolean success = changeService.deleteChange(changeSn);
        return success ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }
    @RequestLog(title = "查看换货单详情",businessType = BusinessType.Query)
    //查看详情
    @GetMapping("/detail/{orderId}")
    public AjaxResult getOrderDetails(@PathVariable String orderId) {
        List<OrderItem> orderItems = changeService.getOrderDetailsByOrderId(orderId);
        return orderItems != null ? AjaxResult.success(orderItems) : AjaxResult.error("未找到对应的订单明细");
    }
    @RequestLog(title = "删除换货详情项",businessType = BusinessType.DELETE)
    // 删除换货详情项
    @DeleteMapping("/change-item/{orderItemId}")
    public AjaxResult deleteChangeItem(@PathVariable Long orderItemId) {
        int result = orderItemService.deleteOrderItemById(orderItemId);
        return result > 0 ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }
    @RequestLog(title = "编辑换货详情项",businessType = BusinessType.UPDATE)
    // 编辑换货详情项
    @PutMapping("/change-item")
    public AjaxResult updateChangeItem(@RequestBody OrderItem orderItem) {
        int result = orderItemService.updateOrderItem(orderItem);
        return result > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
    }
    @RequestLog(title = "重置查询条件",businessType = BusinessType.OTHER)
    //重置查询条件
    @GetMapping("/reset")
    public AjaxResult resetChangeList(@RequestParam(defaultValue = "1") int pageNum,
                                      @RequestParam(defaultValue = "10") int pageSize) {
        List<Change> changeList = changeService.listAllChanges(pageNum, pageSize);
        return AjaxResult.success(changeList);
    }

    //编辑换货单
    @PutMapping("/change/update")
    public AjaxResult updateChange(@RequestBody Change change) {
        int result = changeService.updateChange(change);
        return result > 0 ? AjaxResult.success("更新成功") : AjaxResult.error("更新失败");
    }


}
